<template>
	<view class="contain">
	  <view class="dataBody meishiBody">
		  
		  
		    <view class="w-full flex flex-col itemData" v-for="(item,index) in orderData.data">
				   <view class="w-full flex flex-row py-4 itemBox">
					   <view class="w-[220rpx] flex justify-center items-center">
						   <image :src="item.imgUrl"></image>
					   </view>
					   <view class="w-[480rpx] flex justify-start flex-col ml-2">
						   <view class="w-[100%] flex justify-center">
								<view class="w-full font-bold mid">{{item.title}}</view>
						   </view>
						   <!-- <view class="flex justify-start star mt-1">
							   <view class="flex justify-start">
								   <text class="text-sm font-bold" style="color:#999;">{{item.lvName}}</text>
								</view>
						   </view> -->
						   <view class="flex justify-between mt-1">
								<view class="flex justify-start items-center mt-1">
									<view class="relative top-[2rpx] flex justify-center items-center"><text class="big font-bold text-orange-600">{{item.discount}}</text></view>
									<view class="flex justify-center items-center ml-1"><text class="text-xs text-gray-500 line-through" style="font-size:20rpx;">{{item.originPrice}}</text></view>
								</view>
								<view class="text-sm text-gray-500">
									<!-- <u-number-box v-model="nvalue" @change="nvalChange"></u-number-box> -->
									x{{item.buy}}
								</view>
						   </view>
						   <!-- <view class="text-sm text-green-500 mt-2">积分可抵扣 -{{item.jifen}}元</view> -->
					   </view>
				   </view>		  
		   </view> <!-- itemData End -->
		   
		   
		   <u-divider></u-divider>
		   <view class="flex justify-between pl-2 pr-2 totalprice">
			   <view>商品总价<text class="text-gray-500">(共{{buyNumber}}件)</text></view>
			   <view><text class="text-xl font-bold">￥{{totalMoney}}</text></view>
		   </view>
		   <u-divider></u-divider>
		   
		   
		   <block v-if="LotteryDiscount>0">
				   <block v-if="userData.jifen>0">
					   <view class="flex justify-between items-center pl-2 pr-2 totalprice">
						   <view class="w-[70%]">我的可用积分<text class="text-xl text-green-500 font-bold">{{ FunFormat(userData.jifen)}}</text></view>
						   <view class="w-full flex flex-col items-center">
							   <view class="w-full flex justify-end"><text class="small">使用积分抵扣</text></view>
							   <view class="w-full flex justify-end mt-1"><u-switch v-model="isUseJF" @change="useChange" activeColor="#3C9CFF"></u-switch></view>
						   </view>
					   </view>
					   <u-divider></u-divider>
				   </block>
				   
					
				   <view class="flex justify-between items-center pl-2 pr-2 my-2 huiDetail" v-if="isUseJF && !FreeOrder">
					   <view class="w-[40rpx] h-[35rpx] flex justify-center items-center bg-green-600 icon relative top-[2rpx]" style="border-radius:10rpx;">
						   <text class="text-sm p-2 text-white">分</text>
					   </view>
					   <view class="w-[380rpx]">积分抵扣<text class="w-[200rpx] text-orange-500 font-bold text-right">{{LotteryDiscount}}折</text></view>
					   <view class="w-[200rpx] text-green-500 font-bold text-right">-￥{{zhkouPrice}}</view>
				   </view> <!-- huiDetail End -->
				   <!-- 优惠抵扣详情 -->
				   
				   <view class="flex justify-between pl-2 pr-2 my-2 huiDetail" v-if="FreeOrder">
							   <view class="w-[40rpx] h-[35rpx] flex justify-center items-center bg-orange-500 icon relative top-[6rpx]" style="border-radius:10rpx;">
								   <text class="text-sm p-2 text-white">奖</text>
							   </view>
							   <view class="w-[380rpx]"><text class="w-[200rpx] text-red-500 font-bold text-right">恭喜您抽中本次免单</text></view>
							   <view class="w-[200rpx] text-green-500 font-bold text-right">-￥{{totalMoney}}</view>
				   </view>   <!--huiDetail End -->
		    </block> <!-- LotteryDiscount>0 -->
		   
		   <!-- 小计 -->
		   <view class="flex justify-end items-baseline mt-5 xiaoji">
			   <text class="bg-orange-100 text-orange-600 mr-2 px-1 text-xs font-bold" v-if="zhkouPrice>0 && isUseJF">共省{{zhkouPrice}}元</text>
			   <text class="text-sm mr-2">小计</text>
			   <text class="text-xl text-red-600 font-bold">￥{{realPay}}</text>
		   </view>
		  
		   
		   <view class="flex justify-end items-baseline mt-2 xiaoji" v-if="realPay>0">
			   <text class="text-green-500 text-sm">本次消费赠送{{ formatNum(realPay) }}的油卡积分</text>
		   </view>
		   
	  </view> <!-- meishiBody End -->
	  
	  <!-- 支付按钮 -->
	  <view class="flex justify-between items-center pay">
	  			   <view class="flex flex-col justify-start total">
	  					<view class="flex justify-start items-center">
	  						<text class="text-red-600 text-xs">合计</text>
	  						<text class="text-red-600 text-xl">￥{{realPay}}</text>
	  					</view>
	  					<view class="flex justify-start items-baseline">
	  						<text class="text-gray-500 text-xs">共{{buyNumber}}件</text>
							<block v-if="zhkouPrice>0 && isUseJF">
								<text class="text-gray-500 text-sm ml-2">已优惠</text>
								<text class="text-gray-500 text-xs">￥{{zhkouPrice}}</text>
							</block>
	  					</view>
	  			   </view>
	  			   <view class="w-[300rpx]">
					   <u-button type="primary" shape="circle" icon="weixin-circle-fill" color="#00a100" size="large" text="提交订单" @click="startPay"></u-button>
				</view>
	  </view>
	  
	  <!-- 显示奖金池 -->
	  <view class="w-full fixed bottom-[180rpx] left-0 flex justify-center items-center pool" v-if="paraSetting.data!=null && paraSetting.data.moneyPool>0">
		  <text class="text-red-500 text-sm">瓜分奖金池{{paraSetting.data.moneyPool}}元大奖</text>
	  </view>
	  
	</view> <!-- contain End -->
</template>

<script setup lang='ts'>
import { ref,reactive } from 'vue'
import {  onLoad,onShow } from '@dcloudio/uni-app'
import { userStore } from '@/stores/userStore'
import { Date_C,GenerateOrderNo } from '@/common/date.js'
import {getRandomNumber,isFreeOrder} from '@/common/common.js'
let { hasLogin,userData } = userStore();
const store = userStore()

let FreeOrder=ref(false); //是否免单

//购买列表
let orderData=reactive<any>({
	data:[]
});	

const FunFormat=(num:number)=>{
	return Math.floor(num);
}

//支付订单信息
let payOrderInfo=reactive<any>({
	data:{
		orderNo:null,
		time:null,
		merchantInfo:null, //商家信息
		buyList:null,  //购买列表
		buyNumber:0, //购买数量
		product_Origin_Total_Price:0, //商品原来总价
		isUseJF:true, //是否使用积分抵扣
		merchant_Discount:0, //商家优惠
		JfDiKou:0, //积分优惠
		DiffPrice:0 , //共节省
		payState:'未付款',
		deliveryState:'未发货',
		realPay:0 //实际支付
	}
});	

const strlen=(inputString:string)=>{
	if(inputString.length>10) return inputString.substring(0,10)+"...";
	return inputString;
}

const formatNum=(num:number)=>{
	return Math.floor(num);
}

let backupRealPay=ref(-1);
let nvalue=ref(1);
let buyNumber=ref(1);
let totalMoney=ref(0);
let realPay=ref(0);
let diff=ref(0);
let diKou=ref(0);
let rate=ref(0.1); //10% 每次扣除 我的积分*10%
let totaljifen=ref(0);
let isUseJF=ref(true);
let isClose=ref(false);
let LotteryDiscount=ref(0); //默认抽奖折扣

let paraSetting=reactive<any>({data:null});
let zhkouPrice=ref(0);


//检查后台参数设置和奖金池
const checkSetting=()=>{
	let setting=uni.getStorageSync("setting") || null;
	if(setting!=null){
		paraSetting.data=setting;
		
		//奖金池大于0才进行抽奖
		if(paraSetting.data.moneyPool>0){
			if(paraSetting.data.lotteryLimit>0){
				initialLottery(false);
				paraSetting.data.lotteryLimit--;
				if(paraSetting.data.lotteryLimit<=0){
					 paraSetting.data.lotteryLimit=0;
					 uni.setStorageSync("lastZheKou",LotteryDiscount.value); //最后抽中的折扣
				}
				uni.setStorageSync("setting",paraSetting.data);
			}else{
				uni.$tools.Toast("随机抽奖次数已用完");
				LotteryDiscount.value=uni.getStorageSync("lastZheKou");
				initialLottery(true); //true代表使用缓存
				setTimeout(()=>{
					uni.$tools.Toast("最后折扣 "+uni.getStorageSync("lastZheKou")+"折");
				},1000);
			}
		}
	}else{
		uni.$tools.Toast("后台参数未设置，不能进行优惠抽奖");
	}
}

//初始化抽奖折扣
const initialLottery=(bool:boolean)=>{
	console.log("initialLottery()=> totalMoney.value",totalMoney.value);
	if(!bool || bool===undefined){
		//A等级折扣,100元以下
		if(totalMoney.value<=100){
			LotteryDiscount.value=getRandomNumber(paraSetting.data.Alow,paraSetting.data.Ahight);
			console.log("当前折扣是100元等级:",LotteryDiscount.value);
		}
		//B等级折扣,200元以下
		if(totalMoney.value>100 && totalMoney.value<=200){
			LotteryDiscount.value=getRandomNumber(paraSetting.data.Blow,paraSetting.data.Bhight);
			console.log("当前折扣是200元等级:",LotteryDiscount.value);
		}
		//C等级折扣,300元以下
		if(totalMoney.value>200 && totalMoney.value<=300){
			LotteryDiscount.value=getRandomNumber(paraSetting.data.Clow,paraSetting.data.Chight);
			console.log("当前折扣是300元等级:",LotteryDiscount.value);
		}
		if(LotteryDiscount.value>0){ //这里需要添加条件判断
			zhkouPrice.value=totalMoney.value-totalMoney.value*(LotteryDiscount.value*0.1);
		}
	}else{
		let last=parseFloat(uni.getStorageSync("lastZheKou"));
		if(last>0){ //这里需要添加条件判断
			zhkouPrice.value=totalMoney.value-totalMoney.value*(last*0.1);
		}
	}
	let midPrice=zhkouPrice.value.toString(); //将数字转换为字符
	if(midPrice.indexOf(".")!=-1){ //价格有小数点 26.20000
		zhkouPrice.value=parseFloat(zhkouPrice.value.toFixed(1));
	}
	console.log("折扣价格",zhkouPrice.value);
	countPay();
}

const nvalChange=(e:any)=>{
	console.log(e);
	buyNumber.value=e.value;
	totalMoney.value=orderData.data.originPrice*buyNumber.value;
	diff.value=(orderData.data.originPrice-orderData.data.discount)*buyNumber.value; //差价，省了多少钱
	realPay.value=orderData.data.discount*buyNumber.value-orderData.data.jifen;
}


const useChange=(e:any)=>{
	if(userData.jifen<0 || userData.jifen<totaljifen.value){
		isUseJF.value=false;
		isClose.value=true;
		uni.$tools.Toast("积分不足无法抵扣");
		return false;
	}
	console.log("是否使用积分抵扣",e);
	uni.showModal({
		title:"温馨提示",
		content:isUseJF.value?"是否使用积分抵扣":"是否取消积分抵扣",
		success:res=>{
			if(res.confirm){
				if(isClose.value){
					isUseJF.value=true;
					isClose.value=false;
					console.log("使用积分")
				}else{
					isUseJF.value=false;
					isClose.value=true;
					console.log("取消积分抵扣")	
				}
			}else{
				if(isClose.value){
					isUseJF.value=false;
					isClose.value=true;
					console.log("取消积分抵扣")	
				}else{
					isUseJF.value=true;
					isClose.value=false;	
					console.log("使用积分")			
				}
			}
			countPay();
		},
	})
}


const countPay=()=>{
	realPay.value=0;
	totalMoney.value=0;
	totaljifen.value=0;
	diff.value=0;
	//计算总价格
	if(JSON.stringify(orderData.data)!="[]"){
		orderData.data.forEach(item=>{
			realPay.value+=item.discountVal*item.buy;
			totalMoney.value=realPay.value;
		});
		totaljifen.value=Math.floor(realPay.value*rate.value); //本次订单可抵扣的积分
		if(backupRealPay.value===-1){ //备份原价
			backupRealPay.value=realPay.value;
		}
		console.log("countPay=>realPay.value=>",realPay.value,"zhkouPrice.value=>",zhkouPrice.value);
		if(isUseJF.value){
			diff.value=realPay.value-zhkouPrice.value;
			realPay.value=diff.value;
			diKou.value=totaljifen.value;
		}else{
			realPay.value=backupRealPay.value; //不使用积分
		}
		//*/
		//realPay.value-=zhkouPrice.value; //抽奖折扣价格
		//totaljifen.value=zhkouPrice.value; //一共优惠
		
		//抽中免单
		console.log("countPay=>FreeOrder.value",FreeOrder.value,"realPay.value=>",realPay.value);
		if(FreeOrder.value){
			realPay.value=0;
			zhkouPrice.value=totalMoney.value;
		}
	}
}

//加载
onLoad(()=>{
	let tempData=uni.getStorageSync("buyerInfo") || null;
	if(tempData!=null){
		orderData.data=tempData.buyList; //购物列表
		buyNumber.value=tempData.buyList.length;
	}
	countPay();
});



onShow(()=>{
	
	//console.log("用户积分",userData.jifen);
	checkSetting();
	
	/*
	console.log("onshow当前totalMoney.value",totalMoney.value);
	
	//小于指定金额才有机会免单
	if(isFreeConditions()){
		FreeOrder.value=isFreeOrder();
		console.log("是否免单:",FreeOrder.value);
		if(FreeOrder.value) countPay();
	}
	//*/
});


//是否满足免单条件
const isFreeConditions=()=>{
	let maxFree=((typeof paraSetting.data.maxFree) === 'number')?paraSetting.data.maxFree:parseInt(paraSetting.data.maxFree);
	return (totalMoney.value>0 && totalMoney.value)<=maxFree;
}



let startPay=()=>{	
	uni.showLoading({
		title:"正在发起支付..."
	})	
	//生成订单信息
	let tempData=uni.getStorageSync("buyerInfo") || null;
	if(tempData!=null){
		payOrderInfo.data.orderNo=GenerateOrderNo();
		payOrderInfo.data.time=Date_C();
		payOrderInfo.data.merchantInfo=uni.getStorageSync("productListData") || null; //商家信息
		payOrderInfo.data.buyList=tempData.buyList; //购买商品列表
		payOrderInfo.data.buyNumber=tempData.buyList.length; //购买商品数量
		payOrderInfo.data.product_Origin_Total_Price=totalMoney.value; //商品原总价格
		payOrderInfo.data.merchant_Discount=diff.value; //商家优惠
		payOrderInfo.data.isUseJF=isUseJF.value?true:false;
		payOrderInfo.data.JfDiKou=isUseJF.value?totaljifen.value:0; //积分优惠
		payOrderInfo.data.DiffPrice=diff.value+totaljifen.value; //共节省 =商家优惠+积分抵扣
		payOrderInfo.data.diKou=diKou.value  //折扣
		payOrderInfo.data.LotteryDiscount=LotteryDiscount.value  //折扣
		payOrderInfo.data.zhkouPrice=zhkouPrice.value; //抽检立减折扣
		payOrderInfo.data.lotteryLimit=paraSetting.data.lotteryLimit; //抽奖次数
		payOrderInfo.data.payState='已付款';
		payOrderInfo.data.realPay=realPay.value; //实际支付
		
		uni.setStorageSync("payOrderInfo",payOrderInfo.data);
		
		//减去当前用户抵扣积分
		userData.jifen-=totaljifen.value;
		uni.setStorageSync("userData",userData);
		
		setTimeout(()=>{
			uni.hideLoading();
			uni.$tools.Toast("支付成功 金额:"+realPay.value+"元");
			
			//计算佣金，并保存数据到本地
			countBrokerage();
			
			setTimeout(()=>{
				uni.hideLoading();
				//uni.$tools.Toast("演示完成");
				uni.$tools.GoUrl("/pages/shop_allorder/shop_allorder");
			},1500);
		},1000);
		
		
	}else{
		uni.hideLoading();
		uni.$tools.Toast("订单信息异常,请重新下单");		
	}
}


//计算返佣
const countBrokerage=()=>{
	try{
		//读取设置
		if(paraSetting.data!=null){
			if(paraSetting.data.bindType===null){
				uni.$tools.Toast("暂无上级，无需返佣");
			}else{
				let bindType=paraSetting.data.bindType; //上级绑定类型
				let rate=null; //返佣的利率 
				//保存最终返佣结果
				/*
					let userData=reactive({
						bindType:null,
						action:null,
						actionChinese:"",
						Name:'', //用户
						payMoney:'', //支付金额
						merchant:'', //一级 XX蛋糕店
						mrate:0,
						merchantRebate:0, //一级返佣
						personal:'', //二级 Daniel
						prate:0,
						personalRebate:0, //二级返佣
						hot:'', //二级 Daniel
						hrate:0,
						hotRebate:0, //二级返佣
					});
				*/
				let resultObj={};
				resultObj.bindType=bindType;
				resultObj.action=paraSetting.data.action;
				resultObj.Name=paraSetting.data.personalName;
				resultObj.payMoney=realPay.value;
				//上级
				if(bindType==='personal' && resultObj.action==='p2p'){
						resultObj.personal=paraSetting.data.superiors_personal; //上级是个人
						resultObj.prate=0.03;
						resultObj.personalRebate=(realPay.value*0.03).toFixed(2); //返佣0.03
				}
				if(bindType==='merchant' && resultObj.action==='p2m'){
					resultObj.merchant=paraSetting.data.superiors; //上级是商家
						resultObj.mrate=0.04;
						resultObj.merchantRebate=(realPay.value*0.04).toFixed(2); //返佣0.04
				}
				if(bindType==='merchant' && resultObj.action==='pp2m'){
					//个人已开发3%,再扫商家1%	
					resultObj.personal=paraSetting.data.superiors_personal; //上级是个人
						resultObj.prate=0.03;
						resultObj.personalRebate=(realPay.value*0.03).toFixed(2); //返佣0.03
					resultObj.merchant=paraSetting.data.superiors; //上级是商家
						resultObj.mrate=0.01;
						resultObj.merchantRebate=(realPay.value*0.01).toFixed(2); //返佣0.01
				}
				
				//网红推荐个人
				if(bindType==='hot' && resultObj.action==='h2p'){
					resultObj.hot=paraSetting.data.hotName;
					resultObj.hrate=0.03;
					resultObj.hotRebate=(realPay.value*0.03).toFixed(2); //返佣0.03
				}
				//网红推荐商家
				if(bindType==='hot' && resultObj.action==='h2m'){
					resultObj.hot=paraSetting.data.hotName;
					resultObj.hrate=0.01;
					resultObj.hotRebate=(realPay.value*0.01).toFixed(2); //返佣0.01
				}
				
				
				//计算多级返佣
				if(paraSetting.data.role==='personal'){
					//商家 -> 扫网红 ->  网红扫个人 -> 个人扫商家 -> 去购物 -> 查看最终分佣结果
					//上级网红、商家
					if(paraSetting.data.superiors_hot!="" && paraSetting.data.superiors!=""){ 
						resultObj.personal=paraSetting.data.hotName; //推荐人也是网红
						resultObj.personalRebate=(realPay.value*0.03).toFixed(2); //返佣0.03
						resultObj.hot=paraSetting.data.hotName;
						resultObj.hrate=0.01;
						resultObj.hotRebate=(realPay.value*0.01).toFixed(2); //网红有商家消费的 1%(0.01)
						resultObj.mrate=0.03;
						resultObj.merchantRebate=(realPay.value*0.03).toFixed(2); // 个人消费，商家返佣 3%（0.03）
					}
				}
				
				//更新结果
				uni.setStorageSync("result",resultObj);
			}
		}		
	}catch(e){
		uni.$tools.Toast("没有绑定类型，无需返佣");
		console.log("没有保存结果:",e);
	}
}

//美食列表
// let orderData=reactive<any>({
// 	data:{
// 		  title:"肯德基KFC10对烤翅（奥尔良烤翅）/炸鸡翅10对装",
// 		  lvName:"周一至周日 · 免预约 · 随时退",
// 		  discount:320,
// 		  originPrice:680,
// 		  jifen:5,
// 		  imgUrl:"https://m.360buyimg.com/seckillcms/s250x250_jfs/t1/111391/2/40557/95558/6528bf87F6f3a678e/1cb8a83cef0f6e72.jpg"
// 	}
// });		

</script>

<style lang='scss' scoped>
	@import "shop_pay.scss";
</style>